package com.liuguang.realgateway.handler;

import com.liuguang.realgateway.utils.GatewayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.handler.FilteringWebHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.DispatcherHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName: MyExceptionHandler
 * @Description：    在springboot的自动配置类ErrorWebFluxAutoConfiguration中，
 * 当没有实现ErrorWebExceptionHandler接口的时候会创建DefaultErrorWebExceptionHandler来进行兜底
 * 默认的处理是寻找error的html页面，当寻找不到的时候会返回json字符串，这个在注解里有说到
 * 当实现了ErrorWebExceptionHandler 接口后，当出现异常就会进入到自定义的异常处器中，完成自定义的异常解析
 *
 *
 * @Author: wanghr
 * Date: 4:05 PM 2020/10/29
 * Version: 1.0
 */
@Component
public class MyExceptionHandler implements ErrorWebExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        logger.info("进入自定义异常处理器MyExceptionHandler");
        ServerHttpResponse response = exchange.getResponse();
        System.out.println(ex.getMessage());
        return GatewayUtil.feedbackFriendly(response,"自定义异常处理完毕");
    }
}
